/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//Change the yes,no into form name if any. default = no.
//******************************************************************************
//SUN MICROSYSTEMS'S DOCUMENTATION
//******************************************************************************
/*___INFO__MARK_BEGIN__*/
/*
 *
 *  The Contents of this file are made available subject to the terms of
 *  the Sun Industry Standards Source License Version 1.2
 *
 *  Sun Microsystems Inc., March, 2001
 *
 *
 *  Sun Industry Standards Source License Version 1.2
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.2 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *   The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *   Copyright: 2001 by Sun Microsystems, Inc.
 *
 *   All Rights Reserved.
 *
 */
/*___INFO__MARK_END__*/
//******************************************************************************

//******************************************************************************
//ORGINAL DOCUMENTATION
//******************************************************************************
 /*
 * The source code, object code, and documentation in the com.oreilly.servlet
 * package is copyright and owned by Jason Hunter.
 *
 * Copyright (C) 2001 by Jason Hunter <jhunter@servlets.com>.
 * All rights reserved.
 *
 * Please read http://www.servlets.com/cos/license.html.
 */
//******************************************************************************

//******************************************************************************
//UPDATE LOG
//******************************************************************************
/**
 * Sun Technical Computing Portal admin servlet
 *
 * @author Frederic Pariente, Sun Microsystems
 * @author Dan Fraser, Sun Microsystems (modifications)
 * @author Eric Sharakan, Sun Microsystems (X11; Admin; SGE cells)
 * @version 0.96, 2001/07/27, added support for X11 Apps, non-root Admin,
 *      SGE cells
 * @version 0.95, 2001/07/24, added dynamic user home dir capability
 * @version 0.94, 2001/05/15, added usage of $HOME for export variables
 * @version 0.93, 2001/05/15, added support for access list per application
 * @version 0.9, 2001/04/25
 */
//******************************************************************************
package sgep;

import java.io.*;
import java.util.*;
import java.security.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import com.iplanet.sso.*;
//import com.iplanet.am.sdk.*;
import com.oreilly.servlet.MultipartRequest;

/**
 *
 * @author Ding
 */
public class AdminTCP extends HttpServlet {

    private String APP_HOME_DIR = "/export/home/dingyl/apps/";
//   private String SGE_MPRUN = "mpi/MPRUN";
    private String SGE_ROOT = "/opt/sge/";
    private String SGE_CELL = "default";
    private String SGE_ACCT = "/common/accounting";
    private String COMMD_PORT = "667";
    private String[] SGE_EXPORT = {
        "SGE_ROOT=/opt/sge",
        "SGE_CELL=default",
        "COMMD_PORT=667",
        "LD_LIBRARY_PATH=/opt/sge"
    };
    private String SGE_ARCH;
    private String SUNTCP_SU_SCRIPT = ".suntcp-su";
    private String SUNTCP_LIST = ".suntcp-list";
    private String SUNTCP_APP = ".suntcp-app";
    private String SUNTCP_APP_FORM = ".suntcp-form";

    /**
     *
     * @param request HttpServletRequest
     * @throws SSOException
     * @throws AMException
     * @return String
     */
    /***************************************
    private static String getUser(HttpServletRequest request) throws SSOException,
    AMException {
    String uid = null;
    try{
    SSOTokenManager manager = SSOTokenManager.getInstance();
    SSOToken token = manager.createSSOToken(request);
    if (manager.getInstance().isValidToken(token)) {
    AMStoreConnection amConn = new AMStoreConnection(token);
    String userDN = token.getPrincipal().getName();
    AMUser amUser = amConn.getUser(userDN);
    uid = amUser.getStringAttribute("uid");
    }
    return uid;
    } catch (Exception ie){
    return "";
    }
    }
     ******************************************/
    /**
     *
     * @param request HttpServletRequest
     * @throws SSOException
     * @throws AMException
     * @return String
     */
    /****************************************
    private static String getDomain(HttpServletRequest request) throws
    SSOException, AMException {
    String domain_name = null;
    /*
    SSOTokenManager manager = SSOTokenManager.getInstance();
    SSOToken token = manager.createSSOToken(request);
    if (manager.getInstance().isValidToken(token)) {
    AMStoreConnection amConn = new AMStoreConnection(token);
    String userDN = token.getPrincipal().getName();
    AMUser amUser = amConn.getUser(userDN);
    uid = amUser.getStringAttribute("uid");
    }
     */
    /*******************************************
    return domain_name;
    }
     ******************************************/
    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws SSOException
     * @throws AMException
     * @throws IOException
     */
    /**********************************************
    private static void getRoles(HttpServletRequest request,
    HttpServletResponse response) throws
    SSOException, AMException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    SSOTokenManager manager = SSOTokenManager.getInstance();
    SSOToken token = manager.createSSOToken(request);
    if (manager.getInstance().isValidToken(token)) {
    AMStoreConnection amConn = new AMStoreConnection(token);
    String userDN = token.getPrincipal().getName();
    AMUser amUser = amConn.getUser(userDN);
    Set roles = amUser.getRoleDNs();
    /*          out.println("roles: " + roles); */
    /********************************************************
    }
    }

    /**
     *
     * @param config ServletConfig
     * @throws ServletException
     */
    public void init(ServletConfig config) throws ServletException {
        String s;
        super.init(config);

        s = getInitParameter("app_home");
        if (s != null) {
            APP_HOME_DIR = s;
        }
        s = getInitParameter("sge_root");
        if (s != null) {
            SGE_ROOT = s;
            SGE_EXPORT[0] = "SGE_ROOT=" + s;
        }
        s = getInitParameter("sge_cell");
        if (s != null) {
            SGE_CELL = s;
            SGE_EXPORT[1] = "SGE_CELL=" + s;
        }
        s = getInitParameter("commd_port");
        if (s != null) {
            COMMD_PORT = s;
            SGE_EXPORT[2] = "COMMD_PORT=" + s;
        }

        // Determine SGE architecture
        try {
            Process sgeArch =
                    Runtime.getRuntime().exec(SGE_ROOT + "util/arch", SGE_EXPORT);
            BufferedReader archStdout =
                    new BufferedReader(new InputStreamReader(sgeArch.getInputStream()));

            SGE_ARCH = archStdout.readLine();
            archStdout.close();
        } catch (IOException ioe) {
            // Just assume Solaris
            SGE_ARCH = "solaris";
        }

        SGE_ACCT = SGE_CELL + SGE_ACCT;
        SGE_EXPORT[3] = "LD_LIBRARY_PATH=" + SGE_ROOT + "lib/" + SGE_ARCH;
    }

    //===========================================================================
    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws ServletException
     * @throws IOException
     */
    //===========================================================================
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        try {
            /*****************************************************
            String uid = getUser(request);
            if (uid.equals("")){
            out.println("Session timeout, please relogin");
            return;
            }

            String domain_name = getDomain(request);
            getRoles(request, response);

             ****************************************************/
            /*
            Profile prof = sess.getUserProfile();
            if (!prof.isAllowed("iwtAdmin-execute")) throw new AccessControlException("User " + uid + " does not have Admin privileges");
             */
            String action = request.getParameter("action");

            if (action.equals("applicationList")) {
                applicationList(response);
            } else if (action.equals("applicationInfo")) {
                applicationInfo(request, response);
            } else if (action.equals("newApplicationForm")) {
                newApplicationForm(response, request, null);
            } else if (action.equals("editApplicationForm")) {
                editApplicationForm(request, response);
            } else if (action.equals("updateApplication")) {
                updateApplication(request, response);
            } else if (action.equals("deleteApplication")) {
                deleteApplication(request, response);
            } else if (action.equals("jobList")) {
                jobList(response);
            } else if (action.equals("jobInfo")) {
                jobInfo(request, response);
            } else if (action.equals("killJob")) {
                killJob(request, response);
            } else if (action.equals("jobAccounting")) {
                jobAccounting(response);
            } else if (action.equals("viewFile")) {
                viewFile(request, response);
            } else {
                unknownAction(response);
            }

        } catch (Exception e) {
            out.println("<html><body><pre>");
            e.printStackTrace(out);
            out.println("</pre></body></html>");
        }

    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws ServletException
     * @throws IOException
     */
    //===========================================================================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String uid = "";
        String strPath = "";
        File directory = null;
        String name = "";

        //Check if user login is still valid
        try {
            /***************************************
            uid = getUser(request);
            if (uid.equals("")){
            out.println("Session timeout, Please relogin");
            return;
            }
            String domain_name = getDomain(request);
             * *****************************************/
            MultipartRequest multi = null;

            //Use present time to generate a unique folder for each application
            try {
                name = "A" + System.currentTimeMillis();
                strPath = APP_HOME_DIR + name;
                directory = new File(strPath);
                directory.mkdirs();
                Runtime.getRuntime().exec("/usr/bin/chmod 755 " + strPath).waitFor();

                multi = new MultipartRequest(request, strPath, 100 * 1024 * 1024);
            } catch (Exception ie) {
            }

            if (multi.getParameter("action").equals("Process")) {
                newApplicationForm(response, request, multi);
                //Remove tmpfolder
                Runtime.getRuntime().exec("rm -rf " + strPath).waitFor();
            } else {
                createNewApplication(request, response, out, multi, strPath, directory, name);
            }

        } catch (Exception e) {
            out.println("<html><body><pre>");
            e.printStackTrace(out);
            out.println("</pre></body></html>");
        }
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void applicationList(HttpServletResponse response) throws Exception {
        StringTokenizer st;
        String line, app;

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html><body>");
        try {
            BufferedReader list =
                    new BufferedReader(new FileReader(APP_HOME_DIR + SUNTCP_LIST));

            out.println("<table width=100%>");
            while ((line = list.readLine()) != null) {
                st = new StringTokenizer(line, "\t");
                app = st.nextToken();
                out.println(
                        "<tr><td><li><a href=\"AdminTCP?action=applicationInfo&application=" + app + "\" target=SunTCPApplication>");
                out.println(st.nextToken() + "</a></li></td>");
                out.println("<td><a href=URL onCLick=\"window.open(\'AdminTCP?action=editApplicationForm&application=" + app +
                        "\', \'SunTCPApplication\'); return false\">edit</a></td>");
                out.println("<td><a href=URL onCLick=\"window.open(\'AdminTCP?action=deleteApplication&application=" + app +
                        "\', \'SunTCPApplication\'); return false\">delete</a></td></tr>");
            }
            out.println("</table>");
        } catch (FileNotFoundException e) {
            out.println(APP_HOME_DIR + SUNTCP_LIST);
            out.println("There are no applications available.");
        }
        out.println("<table width=100%><tr><td align=right>");
        out.println("<a href=URL onClick=\"window.open(\'AdminTCP?action=newApplicationForm\',\'TCPApplication\'); return false\">");
        out.println("Add a new application...</a>");
        out.println("</td></tr></table>");
        out.println("</body></html>");
    }

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    private void applicationInfo(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String app = request.getParameter("application");
        String line;
        String path = APP_HOME_DIR + app;

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Application Information");
        try {
            BufferedReader info =
                    new BufferedReader(new FileReader(new File(path, SUNTCP_APP)));

            out.println("<table>");
            out.println("<tr><td>Application name:</td><td>" + info.readLine() +
                    "</td></tr>");
            out.println("<tr><td>Binary name:</td><td>" + info.readLine() +
                    "</td></tr>");
            out.println("<tr><td>Parallel mode:</td><td>" + info.readLine() +
                    "</td></tr>");
            out.println("<tr><td>Uses X11:</td><td>" + info.readLine() + "</td></tr>");
            out.println("<tr><td>Customized form:</td><td>" + info.readLine() +
                    "</td></tr>");
            out.println("<tr><td>User access list:</td><td>" + info.readLine() +
                    "</td></tr>");

            out.println("<tr><td valign=top>Exports:</td>");
            if ((line = info.readLine()) != null) {
                out.println("<td>" + line + "</td>");
            }
            out.println("</tr>");
            while ((line = info.readLine()) != null) {
                out.println("<tr><td>&nbsp;</td><td>" + line + "</td></tr>");

            }
            File directory = new File(path);
            String[] files = directory.list();

            out.println("<tr><td valign=top>Files:</td>");
            if (files.length > 0) {
                out.println("<td>" + files[0] + "</td>");
                out.println(
                        "<td>&nbsp;</td><td><a href=\"AdminTCP?action=viewFile&view=head&application=" + app + "&file=" + files[0] + "\">head</a></td>");
                out.println(
                        "<td>&nbsp;</td><td><a href=\"AdminTCP?action=viewFile&view=tail&application=" + app + "&file=" + files[0] + "\">tail</a></td>");
            }
            out.println("</tr>");
            for (int i = 1; i < files.length; i++) {
                out.println("<tr><td>&nbsp;</td><td>" + files[i] + "</td>");
                out.println(
                        "<td>&nbsp;</td><td><a href=\"AdminTCP?action=viewFile&view=head&application=" + app + "&file=" + files[i] + "\">head</a></td>");
                out.println(
                        "<td>&nbsp;</td><td><a href=\"AdminTCP?action=viewFile&view=tail&application=" + app + "&file=" + files[i] + "\">tail</a></td>");
            }

            out.println("</table>");
        } catch (FileNotFoundException e) {
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }
        out.println("<center><form><input type=button value=Continue onClick=window.close()></form></center>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void newApplicationForm(HttpServletResponse response, HttpServletRequest request, MultipartRequest multi)
            throws Exception {

        StringTokenizer st;
        String line;

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        printPostBackJavaScript(out);
        htmlHeader(out, "New Application Form");

        //============================================================================
        //Try to bring over all values that user have typed in
        //============================================================================
        int intNoOfFiles = 1;
        String strAppName = "";
        String strBinary = "";
        String strUsers = "";
        String strXApp = "";
        String strExport = "";
        String strFormName = "";
        String strParallel = "no";

        if (multi != null) {
            intNoOfFiles = Integer.parseInt(multi.getParameter("ddlNoOfFiles"));
            strAppName = multi.getParameter("name1");
            strBinary = multi.getParameter("binary");
            strParallel = multi.getParameter("parallel");
            strXApp = multi.getParameter("xApp");
            strFormName = multi.getParameter("namef");
            strUsers = multi.getParameter("users");
            strExport = multi.getParameter("export");
        }


        out.println(
                "<form name=form1 method=post action=AdminTCP enctype=multipart/form-data>");
        out.println("<input type=hidden name=action value=\"\" />");

        out.println("<table>");
        out.println("<tr><td>Application name:</td>");
        out.println("<td><input type=text name=name1 value=\"" + strAppName + "\" size=25></td></tr>");
        out.println("<tr><td>Binary or script name:</td>");
        out.println("<td><input type=text name=binary value=\"" + strBinary + "\" size=25></td></tr>");

        out.println("<tr><td>Parallel mode:</td>");
        out.println("<td><select name=parallel>");
        if (strParallel.equals("no")) {
            out.println("<option value=no selected>sequential");
            out.println("<option value=mpi>message passing");
            out.println("<option value=smp>multithreaded");
        } else if (strParallel.equals("mpi")) {
            out.println("<option value=no>sequential");
            out.println("<option value=mpi selected>message passing");
            out.println("<option value=smp>multithreaded");
        } else {
            out.println("<option value=no>sequential");
            out.println("<option value=mpi>message passing");
            out.println("<option value=smp selected>multithreaded");
        }
        out.println("</select></td></tr>");

        out.println("<tr><td>User Access List</td>");
        out.println("<td><input type=text name=users value=\"" + strUsers + "\" size=25></td></tr>");
        out.println("<tr><td>Specify Form Name: (If any)</td>");
        out.println("<td><input type=text name=namef value=\"" + strFormName + "\" size=25></td></tr>");
        out.println("<tr><td valign=top>Environment variables:</td>");
        out.println(
                "<td><textarea name=export rows=5 cols=25>" + strExport + "</textarea></td></tr>");

        out.println("<tr><td><input type=checkbox name=xApp value=yes");
        if (strXApp == null) {
            out.println(">");
        } else {
            if (strXApp.equals("")) {
                out.println(">");
            } else {
                out.println(" checked >");
            }
        }

        out.println("Check here if app uses X11 for graphical display</td></tr>");

        out.println("<tr><td><b><u>Files to Upload</u></b></td></tr>");
        out.println("<tr><td>Number of Files to Upload</td><td><select name=ddlNoOfFiles onchange=\"__doPostBack()\" language=\"javascript\"");
        for (int intCount = 1; intCount < 11; intCount++) {
            if (intCount == intNoOfFiles) {
                out.println("<option value=" + intCount + " selected>" + intCount);
            } else {
                out.println("<option value=" + intCount + ">" + intCount);
            }
        }
        out.println("</select></tr>");

        //Print the number of slots according to the number specify by the user
        for (int intCount = 0; intCount < intNoOfFiles; intCount++) {
            out.println("<tr><td>Input file " + (intCount + 1) + ":</td>");
            out.println("<td><input type=file name=input" + intCount + " size=25></td></tr>");
        }

        out.println("</table>");
        out.println("<center><input type=submit value=Submit></center>");
        out.println("</form>");

        htmlFooter(out);
    }

    //===========================================================================
    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param out PrintWriter
     * @throws Exception
     */
    //===========================================================================
    private void createNewApplication(HttpServletRequest request,
            HttpServletResponse response,
            PrintWriter out, MultipartRequest multi, String path, File directory, String name) throws Exception {

        String name1 = multi.getParameter("name1").trim();
        String binary = multi.getParameter("binary").trim();
        String parallel = multi.getParameter("parallel");
        String xApp = multi.getParameter("xApp");
        String namef = multi.getParameter("namef").trim();
        String export = multi.getParameter("export");
        String users = multi.getParameter("users").trim();

        //check if admin enter any form name. if not will set namef as no.
        if (namef.compareTo("") == 0) {
            namef = "no";
        } else {
            namef = namef;
        }

        htmlHeader(out, "New Application Status");

        Enumeration files = multi.getFileNames();
        if (files.hasMoreElements()) {
            if (multi.getParameter("tar") != null) {
                String filename = multi.getFilesystemName((String) files.nextElement());
                PrintWriter sume =
                        new PrintWriter(new BufferedWriter(new FileWriter(new File(
                        directory, SUNTCP_SU_SCRIPT))));
                sume.println("cd " + path);
                sume.println("gunzip -d " + filename);
                sume.println("tar -xvf " + filename.substring(0, filename.length() - 3));
                sume.close();

                Runtime.getRuntime().exec("/usr/bin/chmod 755 " + path + "/" +
                        SUNTCP_SU_SCRIPT).waitFor();

                Runtime.getRuntime().exec("/usr/bin/chmod 644 " + path + "/" + filename).
                        waitFor();

                Runtime.getRuntime().exec("/usr/bin/ksh exec " + path + "/" +
                        SUNTCP_SU_SCRIPT).waitFor();

                Runtime.getRuntime().exec(path + "/" + SUNTCP_SU_SCRIPT).waitFor();

                if (namef.compareTo("no") == 1) {
                    Runtime.getRuntime().exec("cp " + path + "/" + namef + " " + path +
                            "/" + SUNTCP_APP_FORM);
                }
            } else {
                Runtime.getRuntime().exec("/usr/bin/chmod 755 " + path + "/" + binary).
                        waitFor();
            }
        }
        if (name1.length() > 0) {
            String listfile = APP_HOME_DIR + SUNTCP_LIST;
            PrintWriter list =
                    new PrintWriter(new BufferedWriter(new FileWriter(listfile, true)));
            list.print(name + "\t" + name1);
            if (multi.getParameter("acl") != null) {
                list.print("\t" + users);
            }
            list.println();
            list.close();

            PrintWriter ressource =
                    new PrintWriter(new BufferedWriter(new FileWriter(new File(path,
                    SUNTCP_APP))));
            ressource.println(name1);
            ressource.println(binary);
            ressource.println(parallel);
            ressource.println(new String("yes").equals(xApp) ? "yes" : "no");
            //ressource.println(form);
            ressource.println(namef);
            ressource.println(users);

            try {
                StringTokenizer st_equal,
                        st_newline = new StringTokenizer(export, "\n\r\f");
                String value;
                while (st_newline.hasMoreTokens()) {
                    st_equal =
                            new StringTokenizer(st_newline.nextToken(), "= \t");
                    ressource.print(st_equal.nextToken() + "=");
                    value = st_equal.nextToken();
                    if (value.equals("$HOME")) {
                        ressource.println(path);
                    } else {
                        ressource.println(value);
                    }
                }
                out.println("<p>Application <i>" + name1 +
                        "</i> was created successfully.");
            } catch (NoSuchElementException e) {
                out.println("<p>Error parsing export variables. You can add/correct variables by editing the newly created application.");
            }
            out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>");
            ressource.close();
        } else {
            Runtime.getRuntime().exec("/usr/bin/rm -rf " + path);
            out.println("<p>Go back and enter a non-empty application name.");
            out.println("<center><form><input type=button value=Back onClick=window.back()></form></center>");
        }
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void editApplicationForm(HttpServletRequest request,
            HttpServletResponse response) throws
            Exception {
        StringTokenizer st;
        String line;
        String id = request.getParameter("application");
        String directory = APP_HOME_DIR + id;

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Application Form");
        try {
            BufferedReader read =
                    new BufferedReader(new FileReader(new File(directory, SUNTCP_APP)));

            String app = read.readLine();
            String binary = read.readLine();
            String parallel = read.readLine();
            String xApp = read.readLine();
            String namef = read.readLine();
            String users = read.readLine();
            Vector export = new Vector();
            while ((line = read.readLine()) != null) {
                export.addElement(line);
            }
            read.close();

            out.println("<form method=get action=AdminTCP enctype=multipart/form-data>");
            out.println("<input type=hidden name=action value=updateApplication>");
            out.println("<input type=hidden name=id value=" + id + ">");
            out.println("<table>");
            out.println("<tr><td>Application name:</td>");
            out.println("<td><input type=text name=name1 value=\"" + app + "\" size=25></td></tr>");
            out.println("<tr><td>Binary Path:</td>");
            out.println("<td><input type=text name=binary value=\"" + binary + "\" size=25></td></tr>");

            out.println("<tr><td>Parallel mode:</td>");
            out.println("<td><select name=parallel>");
            out.println("<option" + ((parallel.equals("no")) ? " selected " : " ") +
                    "value=no>sequential");
            out.println("<option" + ((parallel.equals("mpi")) ? " selected " : " ") +
                    "value=mpi>message passing");
            out.println("<option" + ((parallel.equals("smp")) ? " selected " : " ") +
                    "value=smp>multithreaded");
            out.println("</select></td></tr>");
            out.println("<tr><td>Form name:</td>");
            out.println("<td><input type=text name=namef value=" + namef +
                    " size=25></td></tr>");

            out.println("<tr><td><input type=checkbox name=xApp value=yes" +
                    (xApp.equals("yes") ? " checked>" : ">"));
            out.println("check here if App uses X11 for graphical display</td></tr>");

            out.println("<tr><td>Specify User Access List</td><td><input type=text name=users value=\"" + users + "\" size=25></td></tr>");

            out.println("<tr><td valign=top>Environment variables:</td>");
            out.println("<td><textarea name=export rows=5 cols=25>");
            for (int i = 0; i < export.size(); i++) {
                out.println((String) export.get(i));
            }
            out.println("</textarea></td></tr>");

            out.println("<tr><td>Input file:</td>");
            out.println("<td><input type=file name=input size=25></td></tr>");
            out.println("<tr><td colspan=2><input type=checkbox name=tar value=yes>");
            out.println(
                    "check here if this file is a compressed tar archive.</td></tr>");

            out.println("</table>");
            out.println("<center><input type=submit value=Submit></center>");
            out.println("</form>");
        } catch (FileNotFoundException e) {
            out.println("Error accessing selected application.");
        }
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void updateApplication(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String id = request.getParameter("id");
        String name1 = request.getParameter("name1").trim();
        String binary = request.getParameter("binary");
        String parallel = request.getParameter("parallel");
        String xApp = request.getParameter("xApp");
        String namef = request.getParameter("namef").trim();
        String export = request.getParameter("export");
        String users = request.getParameter("users").trim();

        htmlHeader(out, "Project Status");
        if (name1.length() > 0) {
            Vector list = new Vector();
            String line;

            BufferedReader read =
                    new BufferedReader(new FileReader(APP_HOME_DIR + SUNTCP_LIST));
            while ((line = read.readLine()) != null) {
                if (!((new StringTokenizer(line, "\t")).nextToken().equals(id))) {
                    list.addElement(line);
                }
            }
            read.close();

            PrintWriter write =
                    new PrintWriter(new BufferedWriter(new FileWriter(APP_HOME_DIR +
                    SUNTCP_LIST)));
            for (int i = 0; i < list.size(); i++) {
                write.println((String) list.get(i));
            }
            write.print(id + "\t" + name1);
            if (request.getParameter("acl") != null) {
                write.print("\t" + users);
            }
            write.println();
            write.close();

            PrintWriter ressource =
                    new PrintWriter(new BufferedWriter(new FileWriter(new File(
                    APP_HOME_DIR + id, SUNTCP_APP))));
            ressource.println(name1);
            ressource.println(binary);
            ressource.println(parallel);
            ressource.println(new String("yes").equals(xApp) ? "yes" : "no");
            ressource.println(namef);
            ressource.println(users);
            try {
                String value;
                StringTokenizer st_equal,
                        st_newline = new StringTokenizer(export, "\n\r");
                while (st_newline.hasMoreTokens()) {
                    st_equal =
                            new StringTokenizer(st_newline.nextToken(), "= \t");
                    ressource.print(st_equal.nextToken() + "=");
                    value = st_equal.nextToken();
                    if (value.equals("$HOME")) {
                        ressource.println(APP_HOME_DIR + id);
                    } else {
                        ressource.println(value);
                    }
                }
                out.println("<p>Application <i>" + name1 +
                        "</i> was updated successfully.");
            } catch (NoSuchElementException e) {
                out.println("<p>Error parsing export variables. You can add/correct variables by editing again the application.");
            }
            out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>");
            ressource.close();
        } else {
            out.println("<p>Go back and enter a non-empty application name.");
            out.println("<center><form><input type=button value=Back onClick=window.back()></form></center>");
        }
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void deleteApplication(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String app = request.getParameter("application");
        String line;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Application Status");
        try {
            Vector list = new Vector();

            Runtime.getRuntime().exec("/usr/bin/rm -rf " + APP_HOME_DIR + app);
            File listfile = new File(APP_HOME_DIR + SUNTCP_LIST);
            BufferedReader read =
                    new BufferedReader(new FileReader(listfile));
            while ((line = read.readLine()) != null) {
                if (!((new StringTokenizer(line, "\t")).nextToken().equals(app))) {
                    list.addElement(line);
                }
            }
            read.close();

            if (list.size() > 0) {
                PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(
                        listfile)));
                for (int i = 0; i < list.size(); i++) {
                    write.println((String) list.get(i));
                }
                write.close();
            } else {
                listfile.delete();

            }
            out.println("The application was successfully deleted.");
        } catch (Exception e) {
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }
        out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void jobList(HttpServletResponse response) throws Exception {
        String line, id, name;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html><body>");
        try {
            Process qstat =
                    Runtime.getRuntime().exec(SGE_ROOT + "bin/" + SGE_ARCH + "/qstat",
                    SGE_EXPORT);
            BufferedReader jobs =
                    new BufferedReader(new InputStreamReader(qstat.getInputStream()));
            BufferedReader error =
                    new BufferedReader(new InputStreamReader(qstat.getErrorStream()));

            if ((jobs.readLine()) != null) {
                jobs.readLine(); // 2 header lines
                line = jobs.readLine();
                out.println("<table width=100%>");
                do {
                    id = line.substring(0, 6).trim();
                    if (id.length() > 0) {
                        out.println("<tr><td><li><a href=\"AdminTCP?action=jobInfo&id=" + id + "\" target=SunTCPJob>");
                        name = line.substring(13, 24).trim();
                        if (name.length() == 10) {
                            name = name.concat("...");
                        }
                        name = name.replace('_', ' ');
                        out.println(name + "</a></li></td>");
                        out.println("<td align=right><a href=URL onCLick=\"window.open(\'AdminTCP?action=killJob&id=" + id +
                                "\', \'SunTCPJob\'); return false\">kill</a></td></tr>");
                    }
                } while ((line = jobs.readLine()) != null);
                out.println("</table>");
            } else {
                out.println("There are no running jobs.");
                out.println("<pre>");
                while ((line = error.readLine()) != null) {
                    out.println(line);
                }
                out.println("</pre>");
            }
        } catch (Exception e) {
            e.printStackTrace(out);
        }
        out.println("<table width=100%><tr><td align=right>");
        out.println("<a href=URL onCLick=\"window.open(\'AdminTCP?action=jobAccounting\', \'SunTCPJob\'); return false\">");
        out.println("Perform accounting...</a>");
        out.println("</td></tr></table>");
        out.println("</body></html>");
    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void jobInfo(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        String id = request.getParameter("id");
        String line;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Job Information");
        out.println("<pre>");
        try {
            Process qstat =
                    Runtime.getRuntime().exec(SGE_ROOT + "bin/" + SGE_ARCH + "/qstat -j " +
                    id, SGE_EXPORT);
            BufferedReader jobs =
                    new BufferedReader(new InputStreamReader(qstat.getInputStream()));

            while ((line = jobs.readLine()) != null) {
                out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace(out);
        }
        out.println("</pre>");
        out.println("<center><form><input type=button value=Continue onClick=window.close()></form></center>");
        htmlFooter(out);
    }

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    private void killJob(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        String id = request.getParameter("id");
        String line;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Job Status");
        try {
            Process qstat =
                    Runtime.getRuntime().exec(SGE_ROOT + "bin/" + SGE_ARCH + "/qdel " +
                    id, SGE_EXPORT);
            BufferedReader jobs =
                    new BufferedReader(new InputStreamReader(qstat.getInputStream()));

            while ((line = jobs.readLine()) != null) {
                out.println(line);
            }
        } catch (Exception e) {
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }
        out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void jobAccounting(HttpServletResponse response) throws Exception {
        String line, token;
        StringTokenizer st;
        int nb, uid, aid;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        htmlHeader(out, "Job Accounting");
        try {
            try {
                BufferedReader acct = new BufferedReader(new FileReader(SGE_ROOT +
                        SGE_ACCT));
                // SGE_ACCT has owner, account (= application), wall time in columns 4, 7, 14
                out.println("<table width=100% BORDER=\"2\"><tr><th>&nbsp;</th>");
                Vector account = new Vector();
                try {
                    BufferedReader app = new BufferedReader(new FileReader(APP_HOME_DIR +
                            SUNTCP_LIST));
                    while ((line = app.readLine()) != null) {
                        st = new StringTokenizer(line, "\t");
                        account.addElement(st.nextToken());
                        out.println("<th>" + st.nextToken() + "</th>");
                    }
                } catch (FileNotFoundException e) {
                }
                account.addElement("sge");
                out.println("<th>Others</th></tr>");
                nb = account.size();

                Vector user = new Vector();
                Vector time = new Vector();
                while ((line = acct.readLine()) != null) {
                    if (line.startsWith("#")) {
                        continue;
                    }
                    st = new StringTokenizer(line, ":");
                    st.nextToken();
                    st.nextToken();
                    st.nextToken();
                    token = st.nextToken();
                    if (!user.contains(token)) {
                        user.addElement(token);
                        time.addElement(new int[nb]);
                    }
                    uid = user.indexOf(token);
                    st.nextToken();
                    st.nextToken();
                    aid = account.indexOf(st.nextToken());
                    if (aid == -1) {
                        aid = nb - 1;
                    }
                    st.nextToken();
                    st.nextToken();
                    st.nextToken();
                    st.nextToken();
                    st.nextToken();
                    st.nextToken();
                    ((int[]) time.get(uid))[aid] += Integer.parseInt(st.nextToken());
                }

                int[] tab;
                for (uid = 0; uid < user.size(); uid++) {
                    out.println("<tr><td>" + (String) user.get(uid) + "</td>");
                    tab = (int[]) time.get(uid);
                    for (aid = 0; aid < nb; aid++) {
                        out.println("<td align=center>" + tab[aid] + "</td>");
                    }
                    out.println("</tr>");
                }
                out.println("</table>");
            } catch (FileNotFoundException e) {
                out.println("There is no recorded activity.");
            }
        } catch (Exception e) {
            out.println("</table>");
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }
        Process qacct;
        BufferedReader jobs;
        BufferedReader error;
        //Added by Gilbert Thomas Sun APSTC Gilbert.Thomas@sun.com
        //Runs the qacct facility of SGE which checks usage of resources of each user.
        try {
            qacct =
                    Runtime.getRuntime().exec(SGE_ROOT + "bin/" + SGE_ARCH + "/qacct -o",
                    SGE_EXPORT);
            jobs =
                    new BufferedReader(new InputStreamReader(qacct.getInputStream()));
            error =
                    new BufferedReader(new InputStreamReader(qacct.getErrorStream()));

            out.println("<table border=2 width=100%>");
            if ((jobs.readLine()) != null) {
                line = jobs.readLine();
                out.println("<tr>");
                out.println("<th>Owner</th>");
                out.println("<th>Wall Clock</th>");
                out.println("<th>User Time</th>");
                out.println("<th>System Time</th>");
                out.println("<th>CPU</th>");
                out.println("<th>Memory</th>");
                out.println("<th>IO</th>");
                out.println("<th>IOW</th>");

                while ((line = jobs.readLine()) != null) {
                    st = new StringTokenizer(line);
                    out.println("<tr>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("</tr>");
                }
                out.println("</table>");
            } else {
                out.println("There are no running jobs.");
                out.println("<pre>");
                while ((line = error.readLine()) != null) {
                    out.println(line);
                }
                out.println("</pre>");
            } //else
        } //try
        catch (Exception e) {
            e.printStackTrace(out);
        } //catch
        try {
            qacct =
                    Runtime.getRuntime().exec(SGE_ROOT + "bin/" + SGE_ARCH + "/qacct -h",
                    SGE_EXPORT);
            jobs =
                    new BufferedReader(new InputStreamReader(qacct.getInputStream()));
            error =
                    new BufferedReader(new InputStreamReader(qacct.getErrorStream()));

            out.println("<table border=2 width=100%>");
            if ((jobs.readLine()) != null) {
                line = jobs.readLine();
                out.println("<tr>");
                out.println("<th>Host Machine</th>");
                out.println("<th>Wall Clock</th>");
                out.println("<th>User Time</th>");
                out.println("<th>System Time</th>");
                out.println("<th>CPU</th>");
                out.println("<th>Memory</th>");
                out.println("<th>IO</th>");
                out.println("<th>IOW</th>");

                while ((line = jobs.readLine()) != null) {
                    st = new StringTokenizer(line);
                    out.println("<tr>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("<td align=center>" + st.nextToken() + "</td>");
                    out.println("</tr>");
                }
                out.println("</table>");
            } else {
                out.println("There are no running jobs.");
                out.println("<pre>");
                while ((line = error.readLine()) != null) {
                    out.println(line);
                }
                out.println("</pre>");
            } //else
        } //try
        catch (Exception e) {
            e.printStackTrace(out);
        } //catch

        //End of Addition by Gilbert Thomas Sun APSTC Gilbert.Thomas@sun.com

        out.println("<center><form><input type=button value=Continue onClick=window.close()></form></center>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param page PrintWriter
     * @param title String
     */
    //===========================================================================
    private void htmlHeader(PrintWriter page, String title) {
        page.println("<html><body bgcolor=FFFFFF>");
        page.println(
                "<table border=0 cellpadding=2 cellspacing=0 width=100% bgcolor=888888>");
        page.println("<tr><td bgcolor=666699><font color=FFFFFF><b>GEP " + title + "</b></font></td></tr><tr><td bgcolor=DDDDDD>");
    }
    //===========================================================================

    /**
     *
     * @param page PrintWriter
     */
    //===========================================================================
    private void htmlFooter(PrintWriter page) {
        page.println("</td></tr><tr><td bgcolor=000000 align=right>");
        page.println("<font color=FFFFFF>Copyright 2001 Sun Microsystems, Inc. All rights reserved.</font></td></tr>");
        page.println("</table></body></html>");
    }
    //===========================================================================

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void viewFile(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String app = request.getParameter("application");
        String view = request.getParameter("view");
        String file = request.getParameter("file");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        final int NBLINES = 40;
        String line;

        htmlHeader(out, "File View");
        out.println("<pre>");
        try {
            String directory = APP_HOME_DIR + app;

            File objFile = new File(directory, file);
            if (objFile.isDirectory()) {
                out.println("File not viewable, " + file + " is a directory");
                out.println("<center><form><input type=button value=Continue onClick=window.close()></form></center>");
                return;
            }
            if (view.equals("head")) {
                BufferedReader head =
                        new BufferedReader(new FileReader(new File(directory, file)));
                for (int i = 0; ((line = head.readLine()) != null) && (i < NBLINES); i++) {
                    out.println(line);
                }
                head.close();
            } else if (view.equals("tail")) {
                Process ptail =
                        Runtime.getRuntime().exec("/usr/bin/tail -" + NBLINES + " " +
                        directory + "/" + file);
                BufferedReader tail =
                        new BufferedReader(new InputStreamReader(ptail.getInputStream()));
                while ((line = tail.readLine()) != null) {
                    out.println(line);
                }
            } else {
                out.println("Unrecognized view option.");
            }
        } catch (Exception e) {
            e.printStackTrace(out);
        }
        out.println("</pre>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void notYetImplemented(HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        htmlHeader(out, "Status");
        out.println("Not yet Implemented.");
        out.println("<center><form><input type=button value=Continue onClick=window.close()></form></center>");
        htmlFooter(out);
    }
    //===========================================================================

    /**
     *
     * @param response HttpServletResponse
     * @throws Exception
     */
    //===========================================================================
    private void unknownAction(HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("Unkown action.");
        out.println("</body></html>");
    }
    //===========================================================================

    /**
     * Prints simple javascript validation
     * @param PrintWriter
     */
    //===========================================================================
    private void printPostBackJavaScript(PrintWriter out) {
        out.println("<script language=\"javascript\">");
        out.println("function __doPostBack() {");
        out.println("var theform;");
        out.println("if (window.navigator.appName.toLowerCase().indexOf(\"netscape\") > -1) {");
        out.println("theform = document.forms[\"form1\"];");
        out.println("} else {");
        out.println("theform = document.form1;");
        out.println("}");
        out.println("theform.action.value = \"Process\";");
        out.println("theform.submit();");
        out.println("}");
        out.println("</script>");
    }

//
//    /**
//    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
//    * @param request servlet request
//    * @param response servlet response
//    */
//    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
//    throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        try {
//            /* TODO output your page here
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet AdminTCP</title>");
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet AdminTCP at " + request.getContextPath () + "</h1>");
//            out.println("</body>");
//            out.println("</html>");
//            */
//        } finally {
//            out.close();
//        }
//    }
//
//    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
//    /**
//    * Handles the HTTP <code>GET</code> method.
//    * @param request servlet request
//    * @param response servlet response
//    */
//
//    protected void doGet(HttpServletRequest request, HttpServletResponse response)
//    throws ServletException, IOException {
//        processRequest(request, response);
//    }
//
//    /**
//    * Handles the HTTP <code>POST</code> method.
//    * @param request servlet request
//    * @param response servlet response
//    */
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//    throws ServletException, IOException {
//        processRequest(request, response);
//    }
//
//    /**
//    * Returns a short description of the servlet.
//    */
//
//    public String getServletInfo() {
//        return "Short description";
//    }
//    // </editor-fold>
}
